package org.grow.present.controller;

import org.grow.present.service.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: xwg
 * @CreateDate: 2024/6/4
 */

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Value("${present.common.image-location}")
    private String location;
    @Autowired
    private CodeGenerator codeGenerator;

    @PostMapping("/pic")
    public String pic(@RequestParam("file") MultipartFile file) throws IOException {

        String img = codeGenerator.nextCode("IMG");
        Path temp = Path.of(location).resolve("temp");
        if (Files.notExists(temp)) {
            Files.createDirectories(temp);
        }
        System.out.println("upload ::: " + temp.resolve(img).toString());
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        img += ext;
        temp.resolve(img);
        file.transferTo(temp.resolve(img));
        String r = "/temp/" + img;
        return r;
    }
}
